
package edu.hcmus.sow.web.task;

import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailProcess {
    private static final String SMTP_HOST_NAME = "smtp.gmail.com";
    private static final String SMTP_PORT = "465";
    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // gmail của mình (chỉ cần ghi tên không cần @gmail.com cũng được)
    private static final String SMTP_AUTH_USER = "nsbloc";
    // password của mail
    private static final String SMTP_AUTH_PWD  = "nokian72";//tram@anh";
    
    
    public static void sendSSLMail(String from, List<String> dsNguoiNhan, String tieuDe,
            String noiDung) throws MessagingException {
        
        //Khởi tạo các thuộc tính
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
            }
        });
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);
        
        InternetAddress addressFrom = new InternetAddress(from);
        InternetAddress[] addressTo = new InternetAddress[dsNguoiNhan.size()];
        for (int i = 0; i < dsNguoiNhan.size(); i++) {
            addressTo[i] = new InternetAddress(dsNguoiNhan.get(i));
        }
        
        // Gán các thuộc tính cho message
        msg.setFrom(addressFrom);
        msg.setRecipients(Message.RecipientType.TO, addressTo);        
        msg.setSubject(ConvertBetweenUnicodeNCR.NCR2Unicode(tieuDe),"UTF-8");        
        msg.setText(ConvertBetweenUnicodeNCR.NCR2Unicode(noiDung),"UTF-8");
        msg.setSentDate(new Date());
        msg.setHeader("Content-Type", "text/html; charset=UTF-8");
        //msg.setHeader("Content-Transfer-Encoding", "quoted-printable");
        msg.saveChanges();
        Transport.send(msg);
        System.out.println("Gui message thanh cong");
    }
}
